package gov.pr.celepar.sentinela.admin.action;

import gov.pr.celepar.sentinela.admin.dao.AuditoriaControleDAO;
import gov.pr.celepar.sentinela.admin.dao.SistemaDAO;
import gov.pr.celepar.sentinela.admin.dao.factory.DAOFactoryServer;
import gov.pr.celepar.sentinela.admin.form.AuditoriaForm;
import gov.pr.celepar.sentinela.admin.pojo.Sistema;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class AuditoriaAction extends BaseAction {
	private SistemaDAO sistemaB = null;

	private AuditoriaControleDAO auditoriaDao = null;

	private static Log logger = LogFactory.getLog(AuditoriaAction.class);

	public String executar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		AuditoriaForm auditoriaForm = (AuditoriaForm) form;
		logger.debug("AuditoriaAction.executar()");
		DAOFactoryServer daoFactory = DAOFactoryServer.getDAOFactory();
		this.sistemaB = daoFactory.getSistemaDAO();

		this.auditoriaDao = daoFactory.getAuditoriaControleDAO();

		if (this.ALTERAR.equalsIgnoreCase(auditoriaForm.getAcao())) {
			this.comunicacao.autorizaOperacao('A', request, response);
			consultar(auditoriaForm, request);
			logger.debug("alterar_auditoria");
			return "alterar_auditoria";
		} else if (this.CONF_ALTERAR.equalsIgnoreCase(auditoriaForm.getAcao())) {
			this.comunicacao.autorizaOperacao('A', request, response);
			alterar(auditoriaForm, request);
			String msg = this.getResources(request).getMessage("sucesso.alt_auditoria");
			this.addMessageSucess(msg, request);
			return "lista_auditoria";
		}
		return "lista_auditoria";
	}

	private void alterar(AuditoriaForm form, HttpServletRequest request) {
		logger.debug("Alteração de Auditoria");

		Long codSis = Long.decode(form.getCodSistema());
		Long codUser = this.comunicacao.getCodUsuario();
		Boolean ativada = new Boolean(form.isAtivada());

		try {
			this.auditoriaDao.alterarAuditoriaSistema(codSis, codUser, ativada);
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}

	private void consultar(AuditoriaForm form, HttpServletRequest request) {
		try {
			Sistema sistema = this.sistemaB.consultar(Long.parseLong(form.getCodSistema()));
			form.setNomeSistema(sistema.getNome());
			form.setAtivada(sistema.getAuditoria());
		} catch (Exception e) {
			this.addMessageException(e, request);
		}
	}
}
